import { Next, Context } from 'koa';
import { type NextError } from '@/typings/types';

// 错误统一处理
export const errorMiddleware = async (ctx: Context, next: Next) => {
  try {
    await next();
  } catch (err) {
    const error = err as NextError;

    let code = 10001;
    let message = error.message;

    if (error.vailError) {
      code = 400;
    } else if (error.status == 401){
      code = 401;
      message = 'Protected resource, use Authorization header to get access.';
    }
    ctx.sendError({ code, message });
    console.error(error);
  }
}